package com.satan.elasticsearch.config;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EsConfig {

    @Value("${elasticsearch.host}")
    private String hostname;

    @Value("${elasticsearch.port}")
    private int port;


    /**
     * 创建一个RestHighLevelClient实例，并设置其销毁方法为"close"。
     * @return RestHighLevelClient实例
     */
    @Bean(destroyMethod = "close")
    public RestHighLevelClient restHighLevelClient() {
        // 创建一个HttpHost实例，用于指定Elasticsearch的主机和端口
        HttpHost httpHost = HttpHost.create(hostname + ":" + port);
        // 创建一个RestClientBuilder实例，用于构建RestClient对象
        RestClientBuilder builder = RestClient.builder(httpHost);
        // 创建一个RestHighLevelClient实例，并传入RestClientBuilder对象
        return new RestHighLevelClient(builder);
    }

    /**
     * 创建一个ElasticsearchClient实例，并将其注册为Bean。
     * @return ElasticsearchClient实例
     */
    @Bean
    public ElasticsearchClient elasticsearchClient() {
        // 创建一个HttpHost实例，用于指定Elasticsearch的主机和端口
        HttpHost httpHost = HttpHost.create(hostname + ":" + port);
        // 创建一个RestClient实例，用于与Elasticsearch进行通信
        RestClient restClient = RestClient.builder(httpHost).build();
        // 创建一个RestClientTransport实例，用于将RestClient与Elasticsearch连接起来
        RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        // 创建一个ElasticsearchClient实例，并传入RestClientTransport对象
        return new ElasticsearchClient(transport);
    }


    /**
     * 创建一个ElasticsearchAsyncClient实例，并将其注册为Bean。
     * @return ElasticsearchAsyncClient实例
     */
    @Bean
    public ElasticsearchAsyncClient elasticsearchAsyncClient() {
        // 创建一个HttpHost实例，用于指定Elasticsearch的主机和端口
        HttpHost httpHost = HttpHost.create(hostname + ":" + port);
        // 创建一个RestClient实例，用于与Elasticsearch进行通信
        RestClient restClient = RestClient.builder(httpHost).build();
        // 创建一个RestClientTransport实例，用于将RestClient与Elasticsearch连接起来
        RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        // 创建一个ElasticsearchAsyncClient实例，并传入RestClientTransport对象
        return new ElasticsearchAsyncClient(transport);
    }

}

